package com.easyj.base.storage.service.impl;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.easyj.base.common.storage.FileInfo;
import com.easyj.base.common.storage.PathFormat;
import com.easyj.base.constant.ConstantProperties;
import com.easyj.base.constant.Constants;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.FileStoreException;
import com.easyj.base.storage.service.StorageConstants;
import com.easyj.base.storage.service.StorageService;


/**
 * 保存上传文件,保存到本地,-----
 * @author hjf
 *
 */
@Configuration
@ConditionalOnProperty(name = "upload.storage-type", havingValue = "local")
public class LocalStorageService {
	@Service
	public class LocalStorageServiceImpl implements StorageService{
		
		public Logger log =  LoggerFactory.getLogger(getClass());

		
		/**
		 * 保存流程申请文件 root下的applyfiles目录
		 * @param file
		 * @param request
		 * @return
		 * @throws FileStoreException 
		 */
		@Override
		public  FileInfo storeAppendFile(MultipartFile file) throws FileStoreException {
			StorageConstants.CheckAppendFile(file);//check...
			return localStore(file,StorageConstants.AppendDir);
		}
		
		
		@Override
		public FileInfo storeImageFile(MultipartFile file) throws FileStoreException{
			StorageConstants.checkImageFile(file);//check...
			return localStore(file,StorageConstants.ImageDir);
		}
		
		
		
		@Override
		public FileInfo storeAvatarFile(MultipartFile file) throws FileStoreException{
			StorageConstants.checkAvatarFile(file);//check...
			//缩小图像....
			return localStore(file,StorageConstants.AvatarDir);
		}
		
		
		/**
		 *  
		 * @param file
		 * @param categoryDir 分类目录
		 * @return
		 * @throws FileStoreException
		 */
		private  FileInfo localStore(MultipartFile file,String categoryDir) throws FileStoreException{
			
			FileInfo fl=new FileInfo();
			
			String savePath = PathFormat.parse(categoryDir+"/{yyyy}{mm}{dd}/");
			String root=ConstantProperties.LOCAL_PATH;
			File directory = new File(root, savePath);
	        if (!directory.isDirectory()) {
	            boolean rc = directory.mkdirs();
	            if (!rc) {
	            	throw new FileStoreException(EasyjException.MkDirError,"建立目录错误:"+savePath);
	            }
	        }
			//新文件名时间+8位rand数
			String key=PathFormat.parse("{time}{rand:8}");
			String originFileName=file.getOriginalFilename();
			String suffix = PathFormat.getSuffixByFilename(originFileName);
			String filename=key+suffix;
			
	        savePath=savePath+filename;//fileUrl
			String physicalPath =root + savePath;
			//System.out.println(physicalPath);
			
			doStoreFile(file,physicalPath);
			
			fl.setFilePath(savePath);
			fl.setSize(file.getSize());
			fl.setId(key);
			fl.setUrl(ConstantProperties.LOCAL_URL+Constants.URSER_RESOURCE_PREFIX+"/"+savePath);
			fl.setName(file.getOriginalFilename());
			return fl;
		}
		
		
		private void doStoreFile(MultipartFile file,String physicalPath) throws FileStoreException{
		   try{
			File targetFile = new File(physicalPath);
			file.transferTo(targetFile);
		   }catch(Exception ex){
			   log.error("存储文件错误",ex);
			   //ex.printStackTrace();
			   throw new FileStoreException(EasyjException.FileStoreError,"存储文件错误。");
		   }
		}
		
		/**
		 * 
		 * @param fileType (xls or xlsx) 
		 */
		public String saveExcelImpResult(Workbook wb,String fileType) throws FileStoreException {
			
				String savePath = PathFormat.parse(StorageConstants.ImportResultDir+"/{yyyy}{mm}{dd}/");
				String root=ConstantProperties.LOCAL_PATH;
				File directory = new File(root, savePath);
		        if (!directory.isDirectory()) {
		            boolean rc = directory.mkdirs();
		            if (!rc) {
		            	throw new FileStoreException(EasyjException.MkDirError,"建立目录错误:"+savePath);
		            }
		        }
				
				String key=PathFormat.parse("{time}{rand:8}");
					
				String fileName="err_"+key+"."+fileType;
				File targetFile = new  File(directory, fileName);  
				FileOutputStream os=null;
				try {
			        os= new FileOutputStream(targetFile);
			        wb.write(os);
			       
			        savePath=savePath+fileName;//fileUrl
					String url=ConstantProperties.LOCAL_URL+Constants.URSER_RESOURCE_PREFIX+"/"+savePath;
					return url;
				}catch(Exception ex) {
					log.error("存储导入结果文件错误",ex);
					   //ex.printStackTrace();
					throw new FileStoreException(EasyjException.FileStoreError,"存储导入结果文件错误。");
				}finally {
		        	 if (os != null)
						try {
							os.close();
						} catch (IOException e) {
							
						}
		        }
			   
		}
		
		/**
		 * 删除文件
		 */
		@Override
		public boolean deleteFile(String path){
			String root=ConstantProperties.LOCAL_PATH;
			String physicalPath =root + path;
			File file=new File(physicalPath);
			boolean rtn=file.delete();
			return  rtn;
		}
		
		
		
	}	
	
	
}
